package org.poem.service.impl;


import org.poem.datasource.DataSourceVo;
import org.poem.exception.CanalClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库的链接
 *
 * @author sangfor
 */
@Service
public class PostgresDatasource extends AbstractDatasource {
    private static final Logger log = LoggerFactory.getLogger(PostgresDatasource.class);

    /**
     * @param dataSource 数据源信息
     */
    @Override
    public void testSource(DataSourceVo dataSource) throws CanalClientException {
        super.testSource(dataSource);
        String userName = dataSource.getUserName();
        String password = dataSource.getPassword();
        String ip = dataSource.getIp();
        Integer port = dataSource.getPort();
        Connection conn = null;
        Statement statement = null;
        try {
            //加载驱动类
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            //用参数得到连接对象
            String connection = "jdbc:sqlserver://" + ip + ":" + port + ";DatabaseName=" + dataSource.getSourceSchema();
            conn = DriverManager.getConnection(connection, userName, password);
            statement = conn.createStatement();
            statement.execute("select 1 ");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            throw new CanalClientException(e.getMessage(), e);
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    log.info("CDataSourceController:testDataSourceConnect: Connection  close error");
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    log.info("CDataSourceController:testDataSourceConnect: Connection  close error");
                }
            }
        }
    }
}
